<template>
  <div class="update-photo">
    <img :src="img" ref="img" class="img"/>
    <van-nav-bar
      class="toolbar"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
  </div>
</template>

<script>
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { mapGetters } from 'vuex'
import { uploadImgMin } from '@/api/upload'
import { editUser } from '@/api/user'
export default {
  name: 'update-photo',
  components: {},
  props: {
    file: {
      required: true
    },
    type: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      img: this.file.content,
      cropper: null // 裁切器实例
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  created () {
  },
  mounted () {
    // 获取dom节点
    const image = this.$refs.img
    // 初始化裁切器
    this.cropper = new Cropper(image, {
      aspectRatio: 1 / 1, // 预览比例
      viewMode: 1, // 不能移除这个画布容器
      dragMode: 'none', // 什么都不做 默认crop创建一个画布 ， move移动画布
      background: false
    })
  },
  methods: {
    async onConfirm () {
      // console.log(this.file)
      this.$toast.loading({
        message: '保存中',
        forbiclick: true,
        duration: 0
      })

      const file = await this.getCroppedCanvas()
      // console.log(file)

      // const blobData = window.URL.createObjectURL(file)
      // console.log(blobData)

      // blob转file
      const files = new window.File([file], this.file.file.name, { type: file.type })
      // console.log(files)

      const fd = new FormData()
      fd.append('image', files)

      try {
        // 上传文件
        const result = await uploadImgMin(fd)
        // 上传文件成功  更新用户头像链接地址
        if (this.type === 'avatar') {
          await editUser(this.userInfo.id, { avatar: result.image })
        } else if (this.type === 'background_image') {
          await editUser(this.userInfo.id, { background_image: result.image })
        }
        console.log(result)
        this.$toast(this.type === 'background_image' ? '更新背景成功' : '更新头像成功')
        this.$emit('close')
      } catch (error) {
        this.$toast(this.type === 'background_image' ? '更新背景失败' : '更新头像失败')
      }
    },
    getCroppedCanvas () {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob((blob) => {
          resolve(blob)
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.update-photo {
  // background-color: #000;
  display: block;
  height: 100%;
  max-width: 100%;
}
.img{
  display: block;
  max-width: 100%;
  height: 100%;
}
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color:#000;
  ::v-deep .van-nav-bar__text{
    color: #fff;
  }
}
</style>
